<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body onload="todo_list0()">
    <h1>待办事项清单</h1>
    <input type="text" id="creat_title" placeholder="添加事项">
    <input type="button" value="提交" onclick="create()">
    <br>
    <input type="text" id="delete_title" placeholder="删除事项id">
    <input type="button" value="提交" onclick="delete_s()"><br>
    <input type="submit" onclick="todo_list1()" value="已完成事项">
    <input type="submit" onclick="todo_list0()" value="未完成事项">
    <input type="submit" onclick="todo_listall()" value="全部事项">
    <ul id="todo"></ul>
</body>
<script>
    function todo_list0(){
        fetch('/todo')
            .then(respond => respond.json())
            .then(function(data){
                document.getElementById('todo').innerHTML = "";
                var data1 = data.todo
                for (i = 0; i < data1.length; i++){
                    if (!data1[i].completed){
                        document.getElementById('todo').innerHTML += '<li><input type="checkbox" id="'+data1[i].id+'" onchange="change(this.id)">'+data1[i].id+data1[i].title+'</li>';
                }}
            })
    }
    function create(){
        var url = '/create_todo';
        var text1 = document.getElementById('creat_title').value;
        var data = {title: text1};
        fetch(url, { method: 'POST', body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json' }) })
        todo_list0()
    }
    function change(ids){
        fetch('/mark_completed'+'?id='+ids)
        todo_list0()
    }
    function todo_listall(){
        fetch('/todo')
            .then(respond => respond.json())
            .then(function(data){
                document.getElementById('todo').innerHTML = "";
                var data1 = data.todo
                for (i = 0; i < data1.length; i++){
                        document.getElementById('todo').innerHTML += '<li><input type="checkbox" id="'+data1[i].id+'" onchange="change(this.id)">'+data1[i].id+data1[i].title+'</li>';
                }
            })
    }
    function todo_list1(){
        fetch('/todo')
            .then(respond => respond.json())
            .then(function(data){
                document.getElementById('todo').innerHTML = "";
                var data1 = data.todo
                for (i = 0; i < data1.length; i++){
                    if (data1[i].completed){
                        document.getElementById('todo').innerHTML += '<li><input type="checkbox" id="'+data1[i].id+'" onchange="change(this.id)">'+data1[i].id+data1[i].title+'</li>';
                }}
            })
    }
   function delete_s(){
        var ids = document.getElementById('delete_title').value;
        fetch('/delete_todo'+'?id='+ids)
        todo_list0()
    }
</script>
</html>